package com.tarena.lbs.attach.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MinIO配置类
 * 用于配置和初始化MinIO客户端
 */
@Configuration
public class MinioConfig {
    private static final Logger logger = LoggerFactory.getLogger(MinioConfig.class);

    // 从application.yml中读取MinIO配置
    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucket}")
    private String bucket;

    /**
     * 创建MinIO客户端
     * @return MinioClient对象
     */
    @Bean
    public MinioClient minioClient() {
        try {
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!bucketExists) {
                // 若不存在则创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                logger.info("MinIO存储桶 {} 创建成功", bucket);
            } else {
                logger.info("MinIO存储桶 {} 已存在", bucket);
            }

            return minioClient;
        } catch (Exception e) {
            // 细化异常日志输出
            logger.error("初始化MinIO客户端时发生错误，端点: {}, 存储桶: {}", endpoint, bucket, e);
            throw new RuntimeException("初始化MinIO客户端失败", e);
        }
    }
}